package com.zdcp.web.controller.system;

import java.util.List;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.zdcp.core.annotation.FormToken;
import com.zdcp.core.annotation.Log;
import com.zdcp.core.bean.JsonResult;
import com.zdcp.core.bean.TableInfo;
import com.zdcp.core.enums.BusinessType;
import com.zdcp.core.enums.TokenType;
import com.zdcp.core.web.controller.BaseController;
import com.zdcp.core.web.util.ExcelUtils;
import com.zdcp.system.bean.SysUser;
import com.zdcp.system.constant.SysConstants;
import com.zdcp.system.service.ISysPostService;
import com.zdcp.system.service.ISysRoleService;
import com.zdcp.system.service.ISysUserService;
import com.zdcp.system.shiro.service.SysLoginService;
import com.zdcp.system.shiro.util.ShiroUtils;
import com.zdcp.util.StringUtils;
import com.zdcp.util.text.Convert;

/**
 * 系统用户控制层
 * @author yweijian
 * @date 2019年8月18日
 * @version 1.0
 */
@Controller
@RequestMapping("/system/user")
public class SysUserController extends BaseController {
	
	private String prefix = "system/user";
	
	@Autowired
	private ISysUserService userService;

	@Autowired
	private ISysRoleService roleService;

	@Autowired
	private ISysPostService postService;

	@Autowired
	private SysLoginService loginService;

	@RequiresPermissions("system:user:view")
	@GetMapping()
	public String user() {
		return prefix + "/user";
	}

	@SuppressWarnings("unchecked")
	@RequiresPermissions("system:user:list")
	@PostMapping("/list")
	@ResponseBody
	public TableInfo list(SysUser user) {
		initPageQuery(user);
		userService.selectUserList(query);
		return getDataTable(query);
	}

	@Log(title = "用户管理", businessType = BusinessType.EXPORT)
	@RequiresPermissions("system:user:export")
	@PostMapping("/export")
	@ResponseBody
	public JsonResult export(SysUser user) {
		List<SysUser> list = userService.selectUserList(user);
		ExcelUtils<SysUser> util = new ExcelUtils<SysUser>(SysUser.class);
		return util.exportExcel(list, "用户数据");
	}

	@Log(title = "用户管理", businessType = BusinessType.IMPORT)
	@RequiresPermissions("system:user:import")
	@PostMapping("/importData")
	@ResponseBody
	public JsonResult importData(MultipartFile file, boolean updateSupport) throws Exception {
		ExcelUtils<SysUser> util = new ExcelUtils<SysUser>(SysUser.class);
		List<SysUser> userList = util.importExcel(file.getInputStream());
		String operName = ShiroUtils.getSysUser().getLoginName();
		String message = userService.importUser(userList, updateSupport, operName);
		return JsonResult.success(message);
	}

	@RequiresPermissions("system:user:view")
	@GetMapping("/importTemplate")
	@ResponseBody
	public JsonResult importTemplate() {
		ExcelUtils<SysUser> util = new ExcelUtils<SysUser>(SysUser.class);
		return util.importTemplateExcel("用户数据");
	}

	/**
	 * 新增用户
	 */
	@FormToken
	@GetMapping("/add")
	public String add(ModelMap modelMap) {
		modelMap.put("roles", roleService.selectRoleAll());
		modelMap.put("posts", postService.selectPostAll());
		return prefix + "/add";
	}

	/**
	 * 新增保存用户
	 */
	@FormToken(TokenType.DESTROY)
	@RequiresPermissions("system:user:add")
	@Log(title = "用户管理", businessType = BusinessType.INSERT)
	@PostMapping("/add")
	@ResponseBody
	public JsonResult addSave(@Validated SysUser user) {
		if (SysConstants.NOT_UNIQUE.equals(userService.checkLoginNameUnique(user.getLoginName()))) {
			return JsonResult.error("新增用户'" + user.getLoginName() + "'失败，登录账号已存在");
		} else if (SysConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
			return JsonResult.error("新增用户'" + user.getLoginName() + "'失败，手机号码已存在");
		} else if (SysConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
			return JsonResult.error("新增用户'" + user.getLoginName() + "'失败，邮箱账号已存在");
		}
		user.setSalt(ShiroUtils.randomSalt());
		user.setPassword(loginService.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt()));
		user.setCreateBy(ShiroUtils.getLoginName());
		userService.insertUser(user);
		return JsonResult.success();
	}

	/**
	 * 修改用户
	 */
	@GetMapping("/edit/{userId}")
	public String edit(@PathVariable("userId") Long userId, ModelMap modelMap) {
		modelMap.put("user", userService.selectUserById(userId));
		modelMap.put("roles", roleService.selectRolesByUserId(userId));
		modelMap.put("posts", postService.selectPostsByUserId(userId));
		return prefix + "/edit";
	}

	/**
	 * 修改保存用户
	 */
	@RequiresPermissions("system:user:edit")
	@Log(title = "用户管理", businessType = BusinessType.UPDATE)
	@PostMapping("/edit")
	@ResponseBody
	public JsonResult editSave(@Validated SysUser user) {
		if (StringUtils.isNotNull(user.getUserId()) && SysUser.isAdmin(user.getUserId())) {
			return JsonResult.error("不允许修改超级管理员用户");
		} else if (SysConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
			return JsonResult.error("修改用户'" + user.getLoginName() + "'失败，手机号码已存在");
		} else if (SysConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
			return JsonResult.error("修改用户'" + user.getLoginName() + "'失败，邮箱账号已存在");
		}
		user.setUpdateBy(ShiroUtils.getLoginName());
		userService.updateUser(user);
		return JsonResult.success();
	}

	@RequiresPermissions("system:user:resetPwd")
	@Log(title = "重置密码", businessType = BusinessType.UPDATE)
	@GetMapping("/resetPwd/{userId}")
	public String resetPwd(@PathVariable("userId") Long userId, ModelMap modelMap) {
		modelMap.put("user", userService.selectUserById(userId));
		return prefix + "/resetPwd";
	}

	@RequiresPermissions("system:user:resetPwd")
	@Log(title = "重置密码", businessType = BusinessType.UPDATE)
	@PostMapping("/resetPwd")
	@ResponseBody
	public JsonResult resetPwdSave(SysUser user) {
		user.setSalt(ShiroUtils.randomSalt());
		user.setPassword(loginService.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt()));
		if (userService.resetUserPwd(user) > 0) {
			if (ShiroUtils.getUserId() == user.getUserId()) {
				ShiroUtils.setSysUser(userService.selectUserById(user.getUserId()));
			}
			return JsonResult.success();
		}
		return JsonResult.error();
	}

	@RequiresPermissions("system:user:remove")
	@Log(title = "用户管理", businessType = BusinessType.DELETE)
	@PostMapping("/remove")
	@ResponseBody
	public JsonResult remove(String ids) {
		try {
			userService.deleteUserByIds(Convert.toStrArray(ids));
			return JsonResult.success();
		} catch (Exception e) {
			return JsonResult.error(e.getMessage());
		}
	}

	/**
	 * 校验用户名
	 */
	@PostMapping("/checkLoginNameUnique")
	@ResponseBody
	public String checkLoginNameUnique(SysUser user) {
		return userService.checkLoginNameUnique(user.getLoginName());
	}

	/**
	 * 校验手机号码
	 */
	@PostMapping("/checkPhoneUnique")
	@ResponseBody
	public String checkPhoneUnique(SysUser user) {
		return userService.checkPhoneUnique(user);
	}

	/**
	 * 校验email邮箱
	 */
	@PostMapping("/checkEmailUnique")
	@ResponseBody
	public String checkEmailUnique(SysUser user) {
		return userService.checkEmailUnique(user);
	}

	/**
	 * 用户状态修改
	 */
	@Log(title = "用户管理", businessType = BusinessType.UPDATE)
	@RequiresPermissions("system:user:edit")
	@PostMapping("/changeStatus")
	@ResponseBody
	public JsonResult changeStatus(SysUser user) {
		userService.changeStatus(user);
		return JsonResult.success();
	}
}